<?php

class Login extends Controller {

	var $uid;
	var $tpl;
	
	function setVars()
	{
		$this->uid = $this->session->userdata('uid');
		$this->tpl['title'] = 'Login';
		$this->tpl['head'] = '';

	}
	
	function __construct()
	{
		parent::Controller();
		$this->setVars();
		$this->load->library('account');
		log_message('debug', "Login Controler Class Initialized");
		//$this->output->enable_profiler(TRUE);
	}

/*****************************************************************\
|               LOGIN
\*****************************************************************/	
	function Index()
	{
		if(isset($_POST['Alias']))
		{
			$this->postCheck();
		}
		$this->load->view('contact/login', $this->tpl);
	}
	function postCheck()
	{
		$this->load->library('validation');
		$rules['Alias']	= "trim|required|alpha_numeric|xss_clean";
		$rules['Password']	= "trim|required|alpha_numeric|xss_clean";
		$this->validation->set_rules($rules);
		$fields['Alias'] = 'Alias';
		$fields['Password'] = 'Password';
		$this->validation->set_fields($fields);
		if ($this->validation->run() === TRUE)
		{
			$rules['login'] = "callback_login_check"; # Calling login check
			$this->validation->set_rules($rules) ;
            $this->validation->run();
		}
	}

	/***************************************************\
	*	If post is correct we will login
	\***************************************************/
	function login_check($str)
	{
		$alias = $this->validation->Alias;
		$pass  = $this->validation->Password;
		$save  = $this->input->post('save');
		$query = $this->db->getwhere('contact_user', array('Alias' => $alias, 'Password' => $pass), 1);
        if($query->num_rows() > 0) {
            $data = $query->row();
            $data->groups .= ',100';
            $this->session->set_userdata($data);
            if($save == 1) $this->auth->addCookie();
            $this->tpl['sidebar'] = "Welcome back $data->Alias";
			redirect('contact/person', 'location');
        }
		else
		{
			$this->validation->set_message('login_check', 'We have no match');
			return FALSE;
		}
	}

	/*****************************************************************\
	|               LOGOUT
	\*****************************************************************/

	function LogOut()
	{
		$this->auth->Logout();
	}
}
?>
